package com.xing.yunji.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xing.yunji.aop.LogAnnotation;
import com.xing.yunji.common.BaseResponse;
import com.xing.yunji.common.ErrorCode;
import com.xing.yunji.common.ResultUtils;
import com.xing.yunji.exception.BusinessException;
import com.xing.yunji.model.domain.User;
import com.xing.yunji.model.request.user.UserLoginRequest;
import com.xing.yunji.model.request.user.UserRegisterRequest;
import com.xing.yunji.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xing.yunji.constant.UserConstant.*;

/**
 * 用户接口
 *
 * @author xing
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:3000","http://localhost:8081","http://soothing.icu:81"})
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 分页查询10个用户
     * @param pageSize
     * @param pageNum
     * @param request
     * @return
     */
    // todo 推荐多个，未实现
    @GetMapping("/recommend")
    @LogAnnotation(module = "User",operation = "主页推荐用户")
    public BaseResponse<List<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //yunji:user:recommend:2
        String redisKey = USER_RECOMMEND_KEY + loginUser.getId();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        Object userListObj = valueOperations.get(redisKey);
        if (userListObj != null) {
            List<User> userList = (List<User>) userListObj;
            return ResultUtils.success(userList);
        }
        // 无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 推荐的用户排除掉自己
        queryWrapper.notIn("id",loginUser.getId());
        // 查询第1页，每页10条记录
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> resultPage = userService.page(page, queryWrapper);
        List<User> userList = resultPage.getRecords();
        //写缓存
        try {
            valueOperations.set(redisKey, userList, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return ResultUtils.success(userList);
    }

    /**
     * 使用编辑距离算法，根据用户标签匹配相似用户
     * @param num
     * @param request
     * @return
     */
    @LogAnnotation(module ="User", operation ="匹配用户")
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num,HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, loginUser));
    }


    @PostMapping("/update")
    public BaseResponse<Integer> update(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int update = userService.updateUser(user, loginUser);
        return ResultUtils.success(update);
    }

    @PostMapping("/outLogin")
    public BaseResponse<Boolean> outLogin(HttpServletRequest request) {
        request.getSession().setAttribute(USER_LOGIN_STATE, null);
        return ResultUtils.success(true);
    }

    @GetMapping("/current")
    public BaseResponse<User> currentUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(loginUser);
    }

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result, "注册成功！");
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user, "登录成功！");
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        // 仅管理员可查询
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户无权限查询");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(userService::getSaftyUser).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList,HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList, request);
        return ResultUtils.success(userList);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户无权限删除");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

}
